package com.xiejr.actuator.socket.model;

import com.alibaba.fastjson.JSON;
import com.xiejr.actuator.enums.RoleEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.context.ApplicationEvent;

import java.util.function.Supplier;

/**
 * @program: socket-actuator-spring-boot-starter
 * @description: socket传输数据格式
 * @author: xjr
 * @create: 2020-06-23 11:28
 **/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class Message extends ApplicationEvent {
    protected String from;

    protected String to;

    protected String sendTime;

    protected String content;

    protected String status;

    protected String errMsg;

    public Message(Object source){
        super(source);
    }

    public static String makeUpResult(Supplier<String> supplier){
        Message result=new Message("");
        result.setFrom(RoleEnum.SERVER.getCode());
        result.setTo(RoleEnum.CLIENT.getCode());
        try {
            String res=supplier.get();
            result.setContent(res);
            result.setStatus("200");
        }catch (Throwable ex){
            result.setErrMsg(ex.getMessage());
            result.setStatus("500");
        }
        return JSON.toJSONString(result);
    }

}
